package pers.csw.lookBook.controller.front;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import pers.csw.lookBook.common.Res;
import pers.csw.lookBook.dto.UserCommentDto;
import pers.csw.lookBook.entity.Comment;
import pers.csw.lookBook.entity.GiveLike;
import pers.csw.lookBook.entity.User;
import pers.csw.lookBook.server.WebSocketServer;
import pers.csw.lookBook.service.*;
import pers.csw.lookBook.utils.RedisKeyUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;
    @Autowired
    GiveLikeService giveLikeService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedisService redisService;

    @GetMapping("/getListCommentByBookId/{bookId}")
    public Res getListCommentByBookId(@PathVariable Integer bookId){
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        List<Comment> list = commentService.list(queryWrapper);
        List<UserCommentDto> userCommentDtos = new ArrayList<>();
        list.forEach(comment -> {
            QueryWrapper<Comment> qw = new QueryWrapper<>();
            qw.eq("prend_id",comment.getId());
            List<UserCommentDto> userCommentDtoList = new ArrayList<>();
            commentService.list(qw).forEach(commentReply->{
                UserCommentDto userComment = createUserComment(
                        commentReply.getId(),
                        commentReply.getUid(),
                        commentReply.getContent(),
                        commentReply.getUp()
                );
                String o = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, String.valueOf(commentReply.getId()));
                userComment.setUp(Integer.valueOf(o));
                userCommentDtoList.add(userComment);

            });
            UserCommentDto userComment = createUserComment(
                    comment.getId(),
                    comment.getUid(),
                    comment.getContent(),
                    comment.getUp()
            );
            String o = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, String.valueOf(comment.getId()));
            userComment.setUp(Integer.valueOf(o));
            userComment.setUserCommentDto(userCommentDtoList);
            userComment.setReplyCount(userCommentDtoList.size());
            userCommentDtos.add(userComment);
        });
        return Res.success(userCommentDtos);
    }

    @SaCheckLogin
    @GetMapping("/getListCommentByBookId/{bookId}/{userId}")
    public Res getListCommentByBookIdAndUserId(@PathVariable Integer bookId, @PathVariable Integer userId){
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_id",bookId);
        List<Comment> list = commentService.list(queryWrapper);
        List<UserCommentDto> userCommentDtos = new ArrayList<>();
        list.forEach(comment -> {
            if(comment.getPrendId()==0){
                QueryWrapper<Comment> qw = new QueryWrapper<>();
                qw.eq("prend_id",comment.getId());
                List<UserCommentDto> userCommentDtoList = new ArrayList<>();
                List<Comment> list1 = commentService.list(qw);
                if(list1!=null){
                    list1.forEach(commentReply->{
                        UserCommentDto userComment = createUserComment(
                                commentReply.getId(),
                                commentReply.getUid(),
                                commentReply.getContent(),
                                commentReply.getUp()
                        );
                        getStatueAndGetUp(userId, commentReply.getId(), userComment);
                        userCommentDtoList.add(userComment);
                    });
                }

                UserCommentDto userComment = createUserComment(
                        comment.getId(),
                        comment.getUid(),
                        comment.getContent(),
                        comment.getUp()
                );
                getStatueAndGetUp(userId, comment.getId(), userComment);
                userComment.setUserCommentDto(userCommentDtoList);
                userComment.setReplyCount(userCommentDtoList.size());
                userCommentDtos.add(userComment);
            }
        });
        return Res.success(userCommentDtos);
    }

    private void getStatueAndGetUp(Integer userId, Integer pId, UserCommentDto userComment) {
        String i = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED, RedisKeyUtils.getLikedKey(userId, pId));
        String o = (String) redisTemplate.opsForHash().get(RedisKeyUtils.MAP_KEY_USER_LIKED_COUNT, String.valueOf(pId));
        if(i!=null){
            userComment.setStatue(i.equals("1"));
        }else{
            GiveLike giveLike = giveLikeService.getGiveLike(userId, pId);
            if(giveLike!=null){
                userComment.setStatue(giveLike.getStatue()==1);
            }else{
                userComment.setStatue(false);
            }
        }
        if(o!=null){
            userComment.setUp(Integer.valueOf(o));
        }else{
            int giveLikeListNum = giveLikeService.getGiveLikeListNum(pId);
            if(giveLikeListNum>0){
                userComment.setUp(giveLikeListNum);
            }else{
                userComment.setUp(0);
            }

        }
    }

    @SaCheckLogin
    @PostMapping("insertUserComment")
    public Res insertUserComment(@RequestBody Comment comment){
        boolean save = commentService.save(comment);
        return Res.success(save);
    }


    public UserCommentDto createUserComment(Integer id,Integer userId,String content,Integer up){
        UserCommentDto userCommentDto = new UserCommentDto();
        User byId = userService.getById(userId);
        userCommentDto.setId(id);
        userCommentDto.setImg(byId.getImgUrl());
        userCommentDto.setName(byId.getUsername());
        userCommentDto.setContent(content);
        userCommentDto.setUp(up);
        return userCommentDto;
    }

    /**
     * 删除评论
     * @param id 评论id
     * @return  返回是否成功
     */
    @SaCheckLogin
    @DeleteMapping("deleteComment/{id}")
    public Res deleteComment(@PathVariable Integer id){
        boolean b = commentService.removeById(id);
        return Res.success(b);
    }
    
}
